<!-- 新增编辑模型 -->
<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="70%"
    destroy-on-close
  >
    <div
      class="form-box"
      style="max-height: 500px; overflow: hidden; overflow-y: auto"
    >
      <el-form
        ref="operaModelRef"
        :rules="rules"
        :model="dialogForm"
        label-width="120px"
      >
        <el-form-item label="表名称：" prop="modelName">
          <el-input v-model="dialogForm.modelName" placeholder="请输入表名称" />
        </el-form-item>
        <el-form-item label="表编码：" prop="modelCode">
          <el-input v-model="dialogForm.modelCode" placeholder="请输入表编码" />
        </el-form-item>
        <el-form-item label="目标数据库：" prop="dataSourceId">
          <el-select
            v-model="dialogForm.dataSourceId"
            filterable
            style="width: 100%"
            placeholder="请选择目标数据库"
          >
            <el-option
              v-for="item in dataBases"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="dialogForm.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="关联表：" prop="modelRelationList">
          <el-select
            v-model="dialogForm.modelRelationList"
            filterable
            multiple
            style="width: 100%"
            placeholder="请选择要关联的表"
          >
            <el-option
              v-for="item in optionalTables"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建表方式：" prop="createStyle">
          <el-radio-group v-model="dialogForm.createStyle">
            <el-radio label="0">向导模式</el-radio>
            <el-radio label="1">DDL模式</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="dialogForm.createStyle == '0'"
          label="表名："
          prop="tableName"
        >
          <el-input v-model="dialogForm.tableName" placeholder="请输入表名" />
        </el-form-item>

        <FieldsList
          :fields-list="modelFieldList"
          :primary-list="primaryKeyList"
          :primary-key-id="primaryKeyIdInfo"
          ref="fieldsListRef"
          v-if="dialogForm.createStyle === '0'"
        />
        <el-form-item
          v-if="dialogForm.createStyle === '1'"
          label="ddl："
          prop="ddlSql"
          label-width="122px"
        >
          <ace
            ref="aceEditor"
            v-model="dialogForm.ddlSql"
            :options="editorOptions"
            lang="sql"
            width="100%"
            height="500"
            theme="chrome"
            @init="initEditor"
          ></ace>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmDialog">确定</el-button>
    </template>
  </el-dialog>
</template>
<script>
import ace from "vue2-ace-editor";

import FieldsList from "./FieldsList.vue";
export default {
  name: "OperaModel",
  props: {
    dataBases: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    FieldsList,
    ace,
  },
  data() {
    return {
      editorOptions: {
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true,
        showPrintMargin: false,
        fontSize: 16,
        readonly: false,
      },
      dialogTitle: "新增表",
      dialogVisible: false,
      // 提交信息
      dialogForm: {
        modelName: "",
        modelCode: "",
        tableName: "",
        remark: "",
        createStyle: "0",
        ddlSql: "",
        dataSourceId: "",
        primaryKeyName: "",
        modelFieldList: [],
        modelRelationList: [],
      },
      optionalTables: [],
      rules: {
        modelName: [
          { required: true, message: "表名称不能为空！", trigger: "blur" },
        ],
        modelCode: [
          { required: true, message: "表编码不能为空！", trigger: "blur" },
        ],
        tableName: [
          { required: true, message: "表名不能为空!", trigger: "blur" },
        ],
        dataSourceId: [
          { required: true, message: "目标数据库不能为空!", trigger: "blur" },
        ],
      },
      // 编辑时传入的信息
      editModelInfo: {},
      primaryKeyIdInfo: null,
    };
  },
  computed: {
    modelFieldList() {
      return this.dialogForm.modelFieldList || [];
    },
    primaryKeyList() {
      if (
        Array.isArray(this.editModelInfo.primaryDropDown) &&
        this.editModelInfo.primaryDropDown.length > 0
      ) {
        return this.editModelInfo.primaryDropDown.map((i) => {
          return {
            label: i.columnField,
            value: String(i.id),
          };
        });
      }
      return [];
    },
  },
  created() {
    // 请求表数据
    this.getTablesData();
  },
  methods: {
    // 打开弹窗
    openDialog(info) {
      if (info) {
        this.dialogTitle = "编辑表";
        this.editModelInfo = info;
        Object.assign(this.dialogForm, info.localModelResp);
        this.primaryKeyIdInfo = this.dialogForm.primaryKeyId;
        this.dialogForm.modelFieldList = info.localFieldList;
        this.dialogForm.modelRelationList = info.modelRelationList.map(
          (i) => i.originalId
        );
      } else {
        this.dialogTitle = "新增表";
        this.editModelInfo = {};
        this.primaryKeyIdInfo = null
        this.dialogForm = {
          modelName: "",
          modelCode: "",
          tableName: "",
          remark: "",
          createStyle: "0",
          ddlSql: "",
          dataSourceId: "",
          primaryKeyName: "",
          modelFieldList: [],
          modelRelationList: [],
        };
      }

      this.dialogVisible = true;
    },
    initEditor() {
      require("brace/ext/language_tools");
      // 设置语言
      require("brace/mode/sql");
      require("brace/snippets/sql");
      // 主题
      require("brace/theme/monokai");
      require("brace/theme/chrome");
      require("brace/theme/crimson_editor");
    },
    // 获取数据表
    getTablesData() {
      this.$axios
        .post(this.$api.dataConnection.physicalModel.getSourceTableList, {
          pageNum: 1,
          pageSize: 10000,
          modelName: "",
        })
        .then((res) => {
          if (res.data.code === 200) {
            const tableList = res.data.data?.list || [];
            this.optionalTables = tableList.map((item) => {
              return {
                label: item.tableName,
                value: item.id,
                originalTable: item.tableName,
                originalId: item.id,
                originalSchema: item.dataSourceId,
              };
            });
          }
        });
    },
    confirmDialog() {
      this.$refs.operaModelRef.validate((valid, fields) => {
        if (valid) {
          if (this.$refs.fieldsListRef) {
            // // 判断表字段信息是否有效
            // const res = this.$refs.fieldsListRef.checkList();
            // if (res) {
            // 处理数据
            this.dialogForm.modelFieldList =
              this.$refs.fieldsListRef.useFiledList;
            // } else {
            //   return;
            // }
          } else {
            this.dialogForm.modelFieldList = [];
          }
          const modelRelationList = this.dialogForm.modelRelationList;
          this.dialogForm.modelRelationList = this.optionalTables.filter((i) =>
            modelRelationList.includes(i.value)
          );
          if (this.dialogTitle === "新增表") {
            this.$axios
              .post(
                this.$api.dataConnection.physicalModel.postAddModel,
                this.dialogForm
              )
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success(res.data.message || "操作成功");
                  this.dialogVisible = false;
                  this.$emit("reload");
                } else {
                  this.$message.warning(res.data.message);
                }
              });
          } else {
            this.$axios
              .post(
                this.$api.dataConnection.physicalModel.updateModelInfo,
                this.dialogForm
              )
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success(res.data.message || "操作成功");
                  this.dialogVisible = false;
                  this.$emit("reload");
                } else {
                  this.$message.warning(res.data.message);
                }
              });
          }
        }
      });
    },
  },
};
</script>
<style scoped></style>
